package com.caifu.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.*;
import com.caifu.pojo.ZcMealAllocation;
import com.caifu.pojo.ZcOrdering;
import com.caifu.pojo.ZcOrderingRecords;
import com.caifu.service.*;
import com.caifu.util.Util;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 订餐记录表 前端控制器
 * </p>
 *
 * @author szt
 * @since 2020-11-09
 */
@Controller
@RequestMapping("/orderingRecords")
public class ZcOrderingRecordsController extends AbstractController{

    @Autowired
    private ZcOrderingService orderingService;

    @Autowired
    private ZcOrderingRecordsService orderingRecordsService;

    @Autowired
    private ZcOrderingRecordDetailsService orderingRecordDetailsService;

    @Autowired
    private ZcMealAllocationService mealAllocationService;

    @Autowired
    private UtilService utilService;

    @GetMapping("/index")
    public String index(ModelMap map) {
        return "foodDelivery/orderingRecords/index";
    }

    @GetMapping("/account")
    public String account(ModelMap map) {
        return "foodDelivery/orderingRecords/account";
    }

    @GetMapping("/catering")
    public String catering(ModelMap map) {
        return "foodDelivery/orderingRecords/catering";
    }

    @GetMapping("/addNextMonth")
    public String addNextMonth(String month,String name,Long orgId,String orderId,String type,ModelMap map) {
        ZcMealAllocation meal = mealAllocationService.getOne(new QueryWrapper<ZcMealAllocation>().orderByDesc("update_time").orderByDesc("create_time"));
        Map<String,String> org = orderingRecordsService.getOrgInfo(orgId);
        if(meal != null){
            map.put("meals",meal.getMeals());
            map.put("deliveryFee",meal.getDeliveryFee());
        }else{
            map.put("meals","0");
            map.put("deliveryFee","0");
        }
        map.put("month",month);
        map.put("addType",type);
        map.put("monthStr",month.substring(0,4)+"-"+month.substring(4,6));
        map.put("monthStr2",month.substring(0,4)+"年"+month.substring(4,6)+"月");
        map.put("name",name);
        map.put("orgId",orgId);
        map.put("orderId",orderId);
        map.put("nowDay",Util.dateToString(null,"dd"));
        int zcCount = orderingRecordsService.getOrderingCount(orgId+"",month,"1");
        int zhongcanCount = orderingRecordsService.getOrderingCount(orgId+"",month,"2");
        map.put("zaocan",zcCount > 0 ? "yes" : "no");
        map.put("zhongcan",zhongcanCount > 0 ? "yes" : "no");
        String orgName = "";
        String supplyFoodAddress = "";
        if(org.get("org_name") != null && StringUtils.isNotBlank(org.get("org_name")) && !"null".equals(org.get("org_name"))){
            orgName = org.get("org_name");
        }
        if(org.get("org_address") != null && StringUtils.isNotBlank(org.get("org_address")) && !"null".equals(org.get("org_address"))){
            supplyFoodAddress = org.get("org_address");
        }
        map.put("orgName",orgName);
        map.put("supplyFoodAddress",supplyFoodAddress);
        return "foodDelivery/orderingRecords/addNextMonth";
    }

    @PostMapping("getMonthDate")
    @ResponseBody
    public Result getMonthDate(String id){
        try{
            String year_month = "";
            if(StringUtils.isNotBlank(id)){
                ZcOrdering order = orderingService.getById(id);
                year_month = order.getMonth().substring(0,4)+"-"+order.getMonth().substring(4,6);
            }else{
                year_month = Util.dateCalculation_month(new Date(),1,"yyyy-MM");
            }
            String[] arr = year_month.split("-");
            List<String> list = Util.getMonthFullDay(Integer.parseInt(arr[0]),Integer.parseInt(arr[1]),"dd");
            return new Result(200,"获取日历数据成功！",Util.getDateWeek(Util.stringToDate(year_month+"-01","yyyy-MM-dd"),0),list);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取日历数据失败！");
        }
    }

    @PostMapping("getData")
    @ResponseBody
    public Result getData(String type,int page,int pageSize,String name,String orgId,String state){
        try{
            String msg = "获取数据成功！";
            int start = (page - 1) * pageSize;
            List<String> orgList = new ArrayList<>();
            String month = "";
            String symbol = "";
            if("1".equals(type)){
                month = Util.dateToString(null,"yyyyMM");
                symbol = "=";
            }else if("2".equals(type)){
                month = Util.dateCalculation_month(new Date(),1,"yyyyMM");
                symbol = "=";
            }else if("3".equals(type)){
                month = Util.dateCalculation_month(new Date(),-2,"yyyyMM");
                symbol = "<=";
            }else{
                month = "0";
                symbol = "=";
            }
            List<Map<String,String>> list = orderingService.getOrderList(start,pageSize,name,orgList,state,month,symbol);
            int count = orderingService.getOrderListCount(name,orgList,state,month,symbol);
            if(count <= 0){
                msg = "暂无数据！";
            }
            return new Result(200,msg,count,list);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    @PostMapping("getOrderData")
    @ResponseBody
    public Result getOrderData(String foodType,String month,String orderId){
        try{
            String msg = "获取数据成功！";
            List<Map<String,String>> list = orderingRecordsService.getOrderData(orderId,month,foodType);
            if(list != null && list.size() > 0){
                for(Map<String,String> m : list){
                    if("1".equals(String.valueOf(m.get("user_type")))){
                        m.put("user_name",m.get("zd_user_name"));
                        m.put("user_sex",m.get("zd_user_sex"));
                        Object birthDateObj = m.get("zd_birth_date");
                        if(isNotNull(birthDateObj)) {
                            m.put("age", Util.getAgeFromBirthTime(String.valueOf(birthDateObj).substring(0, 4) + "-" + String.valueOf(birthDateObj).substring(4, 6) + "-" + String.valueOf(birthDateObj).substring(6, 8)) + "");
                        }else{
                            m.put("age", "不详");
                        }
                    }else{
                        m.put("user_name",m.get("fd_user_name"));
                        m.put("user_sex",m.get("fd_user_sex"));
                        m.put("age",Util.getAgeFromBirthTime(String.valueOf(m.get("fd_birth_date")))+"");
                    }
                    m.put("isSave","yes");
                }
            }
            return new Result(200,msg,list.size(),list);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    @PostMapping("getDetailsData")
    @ResponseBody
    public Result getDetailsData(int page,int pageSize,String name,String startDate,String endDate,String orgId,String userType,String type,String foodType,String orderStatus){
        try{
            String msg = "获取数据成功！";
            int start = (page - 1) * pageSize;
            List<String> orgList = new ArrayList<>();
            if(StringUtils.isNotBlank(orgId)) {
                List<Map<String,String>> orgs = utilService.getJurisdictionByParentNo(Integer.parseInt(orgId));
                if(orgs != null && orgs.size() > 0){
                    for(Map<String,String> m : orgs){
                        orgList.add(String.valueOf(m.get("org_id")));
                    }
                }
            }else{
                orgList = utilService.getJurisdiction(getUserNo());
            }
            if(StringUtils.isNotBlank(startDate)){startDate = startDate.replace("-","");}
            if(StringUtils.isNotBlank(endDate)){endDate = endDate.replace("-","");}
            if(orgList.size() > 0) {
                List<Map<String, String>> list = orderingRecordDetailsService.getList(start, pageSize, name, startDate, endDate, orgList, userType, type, foodType, orderStatus);
                if (list != null && list.size() > 0) {
                    for (Map<String, String> m : list) {
                        Object obj = null;
                        if ("1".equals(String.valueOf(m.get("user_type")))) {
                            m.put("user_name", m.get("zd_user_name"));
                            m.put("user_sex", m.get("zd_user_sex"));
                            obj = m.get("zd_birth_date");
                            if (isNotNull(obj)) {
                                String birthDate = String.valueOf(obj);
                                m.put("age", Util.getAgeFromBirthTime(birthDate.substring(0, 4) + "-" + birthDate.substring(4, 6) + "-" + birthDate.substring(6, 8)) + "");
                            }
                        } else {
                            m.put("user_name", m.get("fd_user_name"));
                            m.put("user_sex", m.get("fd_user_sex"));
                            m.put("age", Util.getAgeFromBirthTime(String.valueOf(m.get("fd_birth_date"))) + "");
                        }
                        obj = m.get("user_type");
                        if (isNotNull(obj)) {
                            String ut = String.valueOf(obj);
                            if ("1".equals(ut)) {
                                m.put("user_type", "在档");
                            } else if ("2".equals(ut)) {
                                m.put("user_type", "非档");
                            } else if ("3".equals(ut)) {
                                m.put("user_type", "工作人员");
                            } else {
                                m.put("user_type", "未知");
                            }
                        }
                        m.put("food_date", Util.stringDateToStringDate(m.get("month") + m.get("day"), "yyyyMMdd", "yyyy-MM-dd"));
                        obj = m.get("type");
                        if (isNotNull(obj)) {
                            String ut = String.valueOf(obj);
                            if ("1".equals(ut)) {
                                m.put("type", "堂吃");
                            } else if ("2".equals(ut)) {
                                m.put("type", "分餐点自提");
                            } else if ("3".equals(ut)) {
                                m.put("type", "送餐上门");
                            } else {
                                m.put("type", "未知");
                            }
                        }
                        obj = m.get("food_type");
                        if (isNotNull(obj)) {
                            String ut = String.valueOf(obj);
                            if ("1".equals(ut)) {
                                m.put("food_type", "午餐");
                            } else if ("2".equals(ut)) {
                                m.put("food_type", "晚餐");
                            } else {
                                m.put("food_type", "未知");
                            }
                        }
                        obj = m.get("distribution_status");
                        if (isNotNull(obj)) {
                            String ut = String.valueOf(obj);
                            if ("1".equals(ut)) {
                                m.put("distribution_status", "待送餐");
                            } else if ("2".equals(ut)) {
                                m.put("distribution_status", "已送餐");
                            } else {
                                m.put("distribution_status", "未知");
                            }
                        }
                    }
                }
                int count = orderingRecordDetailsService.getListCount(name, startDate, endDate, orgList, userType, type, foodType, orderStatus);
                if (count <= 0) {
                    msg = "暂无数据";
                }
                return new Result(0, msg, count, list);
            }else{
                return new Result(0, "暂无数据权限", 0, null);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    @PostMapping("getLatelyUsers")
    @ResponseBody
    public Result getLatelyUsers(String foodType,String orgNo){
        try{
            String msg = "获取数据成功！";
            ZcOrdering or = orderingService.getLately(orgNo);
            List<Map<String, String>> list = new ArrayList<>();
            if(or != null) {
                list = orderingRecordsService.getOrderData(String.valueOf(or.getId()), or.getMonth(), foodType);
                if (list != null && list.size() > 0) {
                    for (Map<String, String> m : list) {
                        if ("1".equals(String.valueOf(m.get("user_type")))) {
                            m.put("user_name", m.get("zd_user_name"));
                            m.put("user_sex", m.get("zd_user_sex"));
                            String birthDate = String.valueOf(m.get("zd_birth_date"));
                            m.put("age", Util.getAgeFromBirthTime(birthDate.substring(0, 4) + "-" + birthDate.substring(4, 6) + "-" + birthDate.substring(6, 8)) + "");
                        } else {
                            m.put("user_name", m.get("fd_user_name"));
                            m.put("user_sex", m.get("fd_user_sex"));
                            m.put("age", Util.getAgeFromBirthTime(String.valueOf(m.get("fd_birth_date"))) + "");
                        }
                        m.put("isSave", "yes");
                    }
                }
            }
            return new Result(200,msg,list.size(),list);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    @PostMapping("saveNextMonthData")
    @ResponseBody
    public Result saveNextMonthData(String data,String month,String name,String orgId,String supplyFoodAddress,String foodType,String reportingStauts,String orderId){
        try{
            List<JSONObject> result = orderingRecordsService.saveOrder(data,month,name,orgId,supplyFoodAddress,getUserNo(),foodType,reportingStauts,orderId);
            return new Result(200,"保存成功！",result);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"保存失败！");
        }
    }

    @PostMapping("save")
    @ResponseBody
    public Result save(String data,String month,String name,String orgId,String supplyFoodAddress,String foodType,String orderId){
        try{
            ZcOrderingRecords or = orderingRecordsService.saveOrderOne(data,month,name,orgId,supplyFoodAddress,getUserNo(),foodType,orderId);
            return new Result(200,"保存成功！",or);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"保存失败！");
        }
    }

    @PostMapping("delete")
    @ResponseBody
    public Result delete(String id){
        try{
            orderingRecordsService.deleteRecord(id);
            return new Result(200,"删除成功！",null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"删除失败！");
        }
    }

    @PostMapping("getSubsidyStatisticsByUserNo")
    @ResponseBody
    public Result getSubsidyStatisticsByUserNo(String userNo){
        try{
            return new Result(200,"获取数据成功！",orderingRecordsService.getSubsidyStatisticsByUserNo(userNo));
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    @GetMapping("initData")
    @ResponseBody
    public Result initData(){
        try{
            orderingRecordsService.initData();
            return new Result(200,"初始化数据成功！",null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"初始化数据失败！");
        }
    }

    @GetMapping("exportExcel")
    public void test(String month,String id,HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String name = "";

            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 背景设置为白色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 10);

            headWriteCellStyle.setWriteFont(headWriteFont);

            //用来记录需要为第`key`行中的第`value.get(i)`列设置样式
            HashMap<Integer, List<Integer>> colorMap = new HashMap<>();
            List<Integer> colorList = new ArrayList<>();

            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

            ExcelWriter excelWriter = null;

            Calendar calendar = Calendar.getInstance();

            boolean flag = true;

            if(StringUtils.isNotBlank(id)) {
                ZcOrdering order = orderingService.getById(id);
                calendar.setTime(Util.stringToDate(order.getMonth()+"01","yyyyMMdd"));
                int count =  calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                String orgName = orderingService.getOrgNameById(order.getOrgId()+"");
                month = order.getMonth();
                name = month.substring(0,4)+"年助餐考勤明细";
                List<List<String>> head = orderingRecordsService.getExcelHead(count);
                //Map<Integer,String> weekMap = getDateList(month,count);
                WriteSheet writeSheet = EasyExcel.writerSheet(0, orgName)
                        .head(head)
                        .registerWriteHandler(horizontalCellStyleStrategy)
                        .registerWriteHandler(new testMMM(0, month.substring(0,4)+"年"+orgName+"助餐点考勤明细("+month.substring(4,6)+"月)",16+count))
                        .useDefaultStyle(true).relativeHeadRowIndex(1)
                        .build();

                Map<Integer,Integer> cwm = new HashMap<>();
                int cw = 2;
                cwm.put(0,2500);
                cwm.put(1,2000);
                for(int x = 2 ; x < 9 ; x ++){
                    cwm.put(cw++,1500);
                }
                for(int x = 0 ; x < count ;x ++){
                    cwm.put(cw++,1000);
                }
                for(int x = 0 ; x < 7 ; x ++) {
                    cwm.put(cw++, 2000);
                }
                writeSheet.setColumnWidthMap(cwm);
                List<List<String>> data = new ArrayList<>();
                BigDecimal allTotalCount = new BigDecimal("0");
                BigDecimal allTotalSubsidy = new BigDecimal("0");
                BigDecimal allTotalMeals = new BigDecimal("0");
                BigDecimal allTotalDeliveryFee = new BigDecimal("0");
                BigDecimal allTotalCost = new BigDecimal("0");
                for(int t = 1;t <= 2; t++) {
                    List<Map<String,String>> list = orderingRecordsService.getExportData(order.getOrgId()+"",order.getMonth(),t+"");
                    if (list != null && list.size() > 0) {
                        BigDecimal totalCount = new BigDecimal("0");
                        BigDecimal totalSubsidy = new BigDecimal("0");
                        BigDecimal totalMeals = new BigDecimal("0");
                        BigDecimal totalDeliveryFee = new BigDecimal("0");
                        BigDecimal totalCost = new BigDecimal("0");
                        int i = 1;
                        for (Map<String, String> map : list) {
                            List<String> l = new ArrayList<>();
                            l.add(String.valueOf(map.get("org_name"))+ i);
                            i++;
                            String userType = String.valueOf(map.get("user_type"));
                            String userName = "";
                            String userSex = "";
                            String age = "不详";
                            Object obj = null;
                            if ("1".equals(userType)) {
                                userName = map.get(String.valueOf("zd_user_name"));
                                obj = map.get("zd_sex");
                                if (isNotNull(obj)) {
                                    userSex = String.valueOf(obj);
                                    if ("2".equals(userSex)) {
                                        userSex = "女";
                                    } else if ("1".equals(userSex)) {
                                        userSex = "男";
                                    } else {
                                        userSex = "不详";
                                    }
                                } else {
                                    userSex = "不详";
                                }
                                obj = map.get("zd_birth_date");
                                if (isNotNull(obj)) {
                                    String birthDate = String.valueOf(obj);
                                    age = Util.getAgeFromBirthTime(birthDate.substring(0, 4) + "-" + birthDate.substring(4, 6) + "-" + birthDate.substring(6, 8)) + "";
                                } else {
                                    age = "不详";
                                }
                            } else {
                                userName = map.get(String.valueOf("fd_user_name"));
                                obj = map.get("fd_sex");
                                if (isNotNull(obj)) {
                                    userSex = String.valueOf(obj);
                                    if ("2".equals(userSex)) {
                                        userSex = "女";
                                    } else if ("1".equals(userSex)) {
                                        userSex = "男";
                                    } else {
                                        userSex = "不详";
                                    }
                                } else {
                                    userSex = "不详";
                                }
                                obj = map.get("fd_birth_date");
                                if (isNotNull(obj)) {
                                    String birthDate = String.valueOf(obj);
                                    age = Util.getAgeFromBirthTime(birthDate.substring(0, 10)) + "";
                                } else {
                                    age = "不详";
                                }
                            }
                            l.add(userName);
                            l.add(userSex);
                            l.add(age);
                            String foodType = String.valueOf(map.get("food_type"));
                            if("1".equals(foodType)) {
                                l.add("午餐");
                            }else if("2".equals(foodType)){
                                l.add("晚餐");
                            }else{
                                l.add("未知");
                            }
                            String subsidy = String.valueOf(map.get("subsidy"));
                            String meals = String.valueOf(map.get("meals"));
                            String deliveryFee = String.valueOf(map.get("delivery_fee"));
                            String cost = String.valueOf(map.get("cost"));
                            String days = String.valueOf(map.get("days"));
                            String daysCount = String.valueOf(map.get("days_count"));
                            l.add(subsidy);
                            l.add(meals);
                            l.add(deliveryFee);
                            l.add(cost);

                            for (int j = 1; j <= count; j++) {
                                String str = j + "";
                                //String week = weekMap.get(j);
                                if (j < 10) {
                                    str = "0" + str;
                                }
                                /*if(flag && ("0".equals(week) || "6".equals(week))){
                                    colorList.add(8+j);
                                }*/
                                if (days.indexOf(str) != -1) {
                                    l.add("√");
                                } else {
                                    //if(!"0".equals(week) && !"6".equals(week)) {
                                        l.add("△");
                                    //}else{
                                        //l.add("");
                                    //}
                                }
                            }
                            flag = false;
                            l.add(daysCount);
                            BigDecimal sm = new BigDecimal(subsidy).multiply(new BigDecimal(daysCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal m = new BigDecimal(meals).multiply(new BigDecimal(daysCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal df = new BigDecimal(deliveryFee).multiply(new BigDecimal(daysCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal c = new BigDecimal(cost).multiply(new BigDecimal(daysCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            l.add(sm.doubleValue() + "");
                            l.add(m.doubleValue() + "");
                            l.add(df.doubleValue() + "");
                            l.add(c.doubleValue() + "");
                            String type = String.valueOf(map.get("type"));
                            if ("1".equals(type)) {
                                type = "堂吃";
                            } else if ("2".equals(type)) {
                                type = "分餐点自提";
                            } else if ("3".equals(type)) {
                                type = "送餐上门";
                            } else {
                                type = "未知";
                            }
                            l.add(type);
                            l.add("");
                            totalCount = totalCount.add(new BigDecimal(daysCount));
                            totalSubsidy = totalSubsidy.add(sm);
                            totalMeals = totalMeals.add(m);
                            totalDeliveryFee = totalDeliveryFee.add(df);
                            totalCost = totalCost.add(c);
                            allTotalCount = allTotalCount.add(new BigDecimal(daysCount));
                            allTotalSubsidy = allTotalSubsidy.add(sm);
                            allTotalMeals = allTotalMeals.add(m);
                            allTotalDeliveryFee = allTotalDeliveryFee.add(df);
                            allTotalCost = allTotalCost.add(c);
                            data.add(l);
                        }
                        List<String> ll = new ArrayList<>();
                        ll.add("合计"); ll.add(""); ll.add(""); ll.add(""); ll.add(""); ll.add(""); ll.add(""); ll.add(""); ll.add("");
                        for (int j = 1; j <= count; j++) {
                            ll.add("");
                        }
                        ll.add(totalCount.longValue()+"");
                        ll.add(totalSubsidy.doubleValue()+"");
                        ll.add(totalMeals.doubleValue()+"");
                        ll.add(totalDeliveryFee.doubleValue()+"");
                        ll.add(totalCost.doubleValue()+"");
                        ll.add("");
                        ll.add("");
                        data.add(ll);
                    }
                }
                List<String> lll = new ArrayList<>();
                lll.add("总计"); lll.add("");lll.add(""); lll.add(""); lll.add(""); lll.add(""); lll.add(""); lll.add(""); lll.add("");
                for (int j = 1; j <= count; j++) {
                    lll.add("");
                }
                lll.add(allTotalCount.longValue()+"");
                lll.add(allTotalSubsidy.doubleValue()+"");
                lll.add(allTotalMeals.doubleValue()+"");
                lll.add(allTotalDeliveryFee.doubleValue()+"");
                lll.add(allTotalCost.doubleValue()+"");
                lll.add("");
                lll.add("");
                colorMap.put(2,colorList);
                //CellColorSheetWriteHandler writeHandler = new CellColorSheetWriteHandler(colorMap, IndexedColors.GREEN.getIndex());
                //excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(writeHandler).build();
                excelWriter = EasyExcel.write(response.getOutputStream()).build();
                data.add(lll);
                excelWriter.write(data, writeSheet);
            }else if(StringUtils.isNotBlank(month)){
                name = month.substring(0,4)+"年助餐考勤明细";
                calendar.setTime(Util.stringToDate(month+"01","yyyyMMdd"));
                int count =  calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                List<String> orgList = utilService.getJurisdiction(getUserNo());
                if(orgList != null && orgList.size() > 0){
                    List<List<String>> head = orderingRecordsService.getExcelHead(count);
                    //Map<Integer,String> weekMap = getDateList(month,count);
                    //for(String orgId : orgList) {
                    for(int orgIndex = 0 ; orgIndex < orgList.size() ;orgIndex ++) {
                        String orgId = orgList.get(orgIndex);
                        ZcOrdering order = orderingService.getById(orgId);
                        String orgName = orderingService.getOrgNameById(orgId);
                        WriteSheet writeSheet = EasyExcel.writerSheet(0, orgName)
                                .head(head)
                                .registerWriteHandler(horizontalCellStyleStrategy)
                                .registerWriteHandler(new testMMM(orgIndex, month.substring(0,4)+"年"+orgName+"助餐点考勤明细("+month.substring(4,6)+"月)",16+count))
                                .useDefaultStyle(true).relativeHeadRowIndex(1)
                                .build();
                        Map<Integer,Integer> cwm = new HashMap<>();
                        int cw = 2;
                        cwm.put(0,2000);
                        cwm.put(1,2000);
                        for(int x = 2 ; x < 9 ; x ++){
                            cwm.put(cw++,1500);
                        }
                        for(int x = 0 ; x < count ;x ++){
                            cwm.put(cw++,1000);
                        }
                        for(int x = 0 ; x < 7 ; x ++) {
                            cwm.put(cw++, 1500);
                        }
                        writeSheet.setColumnWidthMap(cwm);
                        List<List<String>> data = new ArrayList<>();
                        BigDecimal allTotalCount = new BigDecimal("0");
                        BigDecimal allTotalSubsidy = new BigDecimal("0");
                        BigDecimal allTotalMeals = new BigDecimal("0");
                        BigDecimal allTotalDeliveryFee = new BigDecimal("0");
                        BigDecimal allTotalCost = new BigDecimal("0");
                        for(int t = 1;t <= 2; t++) {
                            List<Map<String,String>> list = orderingRecordsService.getExportData(order.getOrgId()+"",order.getMonth(),t+"");
                            if (list != null && list.size() > 0) {
                                BigDecimal totalCount = new BigDecimal("0");
                                BigDecimal totalSubsidy = new BigDecimal("0");
                                BigDecimal totalMeals = new BigDecimal("0");
                                BigDecimal totalDeliveryFee = new BigDecimal("0");
                                BigDecimal totalCost = new BigDecimal("0");
                                int i = 1;
                                for (Map<String, String> map : list) {
                                    List<String> l = new ArrayList<>();
                                    l.add(String.valueOf(map.get("org_name"))+ i);
                                    i++;
                                    String userType = String.valueOf(map.get("user_type"));
                                    String userName = "";
                                    String userSex = "";
                                    String age = "不详";
                                    Object obj = null;
                                    if ("1".equals(userType)) {
                                        userName = map.get(String.valueOf("zd_user_name"));
                                        obj = map.get("zd_sex");
                                        if (isNotNull(obj)) {
                                            userSex = String.valueOf(obj);
                                            if ("2".equals(userSex)) {
                                                userSex = "女";
                                            } else if ("1".equals(userSex)) {
                                                userSex = "男";
                                            } else {
                                                userSex = "不详";
                                            }
                                        } else {
                                            userSex = "不详";
                                        }
                                        obj = map.get("zd_birth_date");
                                        if (isNotNull(obj)) {
                                            String birthDate = String.valueOf(obj);
                                            age = Util.getAgeFromBirthTime(birthDate.substring(0, 4) + "-" + birthDate.substring(4, 6) + "-" + birthDate.substring(6, 8)) + "";
                                        } else {
                                            age = "不详";
                                        }
                                    } else {
                                        userName = map.get(String.valueOf("fd_user_name"));
                                        obj = map.get("fd_sex");
                                        if (isNotNull(obj)) {
                                            userSex = String.valueOf(obj);
                                            if ("2".equals(userSex)) {
                                                userSex = "女";
                                            } else if ("1".equals(userSex)) {
                                                userSex = "男";
                                            } else {
                                                userSex = "不详";
                                            }
                                        } else {
                                            userSex = "不详";
                                        }
                                        obj = map.get("fd_birth_date");
                                        if (isNotNull(obj)) {
                                            String birthDate = String.valueOf(obj);
                                            age = Util.getAgeFromBirthTime(birthDate.substring(0, 10)) + "";
                                        } else {
                                            age = "不详";
                                        }
                                    }
                                    l.add(userName);
                                    l.add(userSex);
                                    l.add(age);
                                    String foodType = String.valueOf(map.get("food_type"));
                                    if("1".equals(foodType)) {
                                        l.add("午餐");
                                    }else if("2".equals(foodType)){
                                        l.add("晚餐");
                                    }else{
                                        l.add("未知");
                                    }
                                    String subsidy = String.valueOf(map.get("subsidy"));
                                    String meals = String.valueOf(map.get("meals"));
                                    String deliveryFee = String.valueOf(map.get("delivery_fee"));
                                    String cost = String.valueOf(map.get("cost"));
                                    String days = String.valueOf(map.get("days"));
                                    String daysCount = String.valueOf(map.get("days_count"));
                                    l.add(subsidy);
                                    l.add(meals);
                                    l.add(deliveryFee);
                                    l.add(cost);
                                    for (int j = 1; j <= count; j++) {
                                        String str = j + "";
                                        //String week = weekMap.get(j);
                                        if (j < 10) {
                                            str = "0" + str;
                                        }
                                       /* if(flag && ("0".equals(week) || "6".equals(week))){
                                            colorList.add(8+j);
                                        }*/
                                        if (days.indexOf(str) != -1) {
                                            l.add("√");
                                        } else {
                                            //if(!"0".equals(week) && !"6".equals(week)) {
                                                l.add("△");
                                            //}else{
                                               // l.add("");
                                            //}
                                        }
                                    }
                                    flag = false;
                                    l.add(daysCount);
                                    BigDecimal sm = new BigDecimal(subsidy).multiply(new BigDecimal(daysCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    BigDecimal m = new BigDecimal(meals).multiply(new BigDecimal(daysCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    BigDecimal df = new BigDecimal(deliveryFee).multiply(new BigDecimal(daysCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    BigDecimal c = new BigDecimal(cost).multiply(new BigDecimal(daysCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    l.add(sm.doubleValue() + "");
                                    l.add(m.doubleValue() + "");
                                    l.add(df.doubleValue() + "");
                                    l.add(c.doubleValue() + "");
                                    String type = String.valueOf(map.get("type"));
                                    if ("1".equals(type)) {
                                        type = "堂吃";
                                    } else if ("2".equals(type)) {
                                        type = "分餐点自提";
                                    } else if ("3".equals(type)) {
                                        type = "送餐上门";
                                    } else {
                                        type = "未知";
                                    }
                                    l.add(type);
                                    l.add("");
                                    totalCount = totalCount.add(new BigDecimal(daysCount));
                                    totalSubsidy = totalSubsidy.add(sm);
                                    totalMeals = totalMeals.add(m);
                                    totalDeliveryFee = totalDeliveryFee.add(df);
                                    totalCost = totalCost.add(c);
                                    allTotalCount = allTotalCount.add(new BigDecimal(daysCount));
                                    allTotalSubsidy = allTotalSubsidy.add(sm);
                                    allTotalMeals = allTotalMeals.add(m);
                                    allTotalDeliveryFee = allTotalDeliveryFee.add(df);
                                    allTotalCost = allTotalCost.add(c);
                                    data.add(l);
                                }
                                List<String> ll = new ArrayList<>();
                                ll.add("合计"); ll.add(""); ll.add(""); ll.add(""); ll.add(""); ll.add(""); ll.add(""); ll.add(""); ll.add("");
                                for (int j = 1; j <= count; j++) {
                                    ll.add("");
                                }
                                ll.add(totalCount.longValue()+"");
                                ll.add(totalSubsidy.doubleValue()+"");
                                ll.add(totalMeals.doubleValue()+"");
                                ll.add(totalDeliveryFee.doubleValue()+"");
                                ll.add(totalCost.doubleValue()+"");
                                ll.add("");
                                ll.add("");
                                data.add(ll);
                            }
                        }
                        List<String> lll = new ArrayList<>();
                        lll.add("总计"); lll.add(""); lll.add(""); lll.add(""); lll.add(""); lll.add(""); lll.add(""); lll.add(""); lll.add("");
                        for (int j = 1; j <= count; j++) {
                            lll.add("");
                        }
                        lll.add(allTotalCount.longValue()+"");
                        lll.add(allTotalSubsidy.doubleValue()+"");
                        lll.add(allTotalMeals.doubleValue()+"");
                        lll.add(allTotalDeliveryFee.doubleValue()+"");
                        lll.add(allTotalCost.doubleValue()+"");
                        lll.add("");
                        lll.add("");
                        colorMap.put(2,colorList);
                        CellColorSheetWriteHandler writeHandler = new CellColorSheetWriteHandler(colorMap, IndexedColors.GREEN.getIndex());
                        excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(writeHandler).build();
                        data.add(lll);
                        excelWriter.write(data, writeSheet);
                    }
                }
            }else{
                throw new Exception("导出失败！");
            }
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap<>(10);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    private Map<Integer,String> getDateList(String month,int count){
        Map<Integer,String> result = new HashMap<>();
        try{
           Date date = Util.stringToDate(month+"01","yyyyMMdd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
            Map<Integer,String> m = new HashMap();
            result.put(1,w+"");
           for(int i = 2 ; i <= count; i++){
               cal.add(Calendar.DATE,   1);
               int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
               Map<Integer,String> map = new HashMap();
               result.put(i,week+"");
           }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    private boolean isNotNull(Object obj){
        if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
            return true;
        }else{
            return false;
        }
    }
}
